#include "stdafx.h"
#include "net/URI.hpp"
#include "charset/string.hpp"
using namespace JHCPP::charset;
#include "utils/numberformatter.hpp"
#include "utils/numberparser.hpp"
using JHCPP::utils::CNumberParser;
using JHCPP::utils::CNumberFormatter;
#include "stdlib/exception.hpp"
using namespace JHCPP::stdlib::jhException;
#include <algorithm>

NET_NAMESPACE_BEGIN

const std::string CURI::RESERVED_PATH     = "?#";
const std::string CURI::RESERVED_QUERY    = "?#/";
const std::string CURI::RESERVED_FRAGMENT = "";
const std::string CURI::ILLEGAL           = "%<>{}|\\\"^`";

CURI::CURI() : m_port(0)
{
}

CURI::CURI(const std::string& uri) : m_port(0)
{
	parse(uri);
}

CURI::CURI(const char* uri) : m_port(0)
{
	parse(std::string(uri));
}

CURI::CURI(const std::string& scheme, const std::string& pathEtc) : m_scheme(scheme), m_port(0)
{
	toLowerInPlace(m_scheme);
	m_port = getWellKnownPort();
	std::string::const_iterator beg = pathEtc.begin();
	std::string::const_iterator end = pathEtc.end();
	parsePathEtc(beg, end);
}

CURI::CURI(const std::string& scheme, const std::string& authority, const std::string& pathEtc) : m_scheme(scheme)
{
	toLowerInPlace(m_scheme);
	std::string::const_iterator beg = authority.begin();
	std::string::const_iterator end = authority.end();
	parseAuthority(beg, end);
	beg = pathEtc.begin();
	end = pathEtc.end();
	parsePathEtc(beg, end);
}

CURI::CURI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query)
	: m_scheme(scheme), m_path(path), m_query(query)
{
	toLowerInPlace(m_scheme);
	std::string::const_iterator beg = authority.begin();
	std::string::const_iterator end = authority.end();
	parseAuthority(beg, end);
}

CURI::CURI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query, const std::string& fragment)
	: m_scheme(scheme),
	m_path(path),
	m_query(query),
	m_fragment(fragment)
{
	toLowerInPlace(m_scheme);
	std::string::const_iterator beg = authority.begin();
	std::string::const_iterator end = authority.end();
	parseAuthority(beg, end);
}

CURI::CURI(const CURI& uri)
	: m_scheme(uri.m_scheme),
	m_userInfo(uri.m_userInfo),
	m_host(uri.m_host),
	m_port(uri.m_port),
	m_path(uri.m_path),
	m_query(uri.m_query),
	m_fragment(uri.m_fragment)
{
}

CURI::CURI(const CURI& baseURI, const std::string& relativeURI)
	: m_scheme(baseURI.m_scheme),
	m_userInfo(baseURI.m_userInfo),
	m_host(baseURI.m_host),
	m_port(baseURI.m_port),
	m_path(baseURI.m_path),
	m_query(baseURI.m_query),
	m_fragment(baseURI.m_fragment)
{
	resolve(relativeURI);
}

CURI::CURI(const CPath& path) : m_scheme("file"), m_port(0)
{
	CPath absolutePath(path);
	absolutePath.makeAbsolute();
	m_path = absolutePath.toString(CPath::PATH_LUNIX);
}

CURI::~CURI()
{
}

CURI& CURI::operator = (const CURI& uri)
{
	if (&uri != this)
	{
		m_scheme   = uri.m_scheme;
		m_userInfo = uri.m_userInfo;
		m_host     = uri.m_host;
		m_port     = uri.m_port;
		m_path     = uri.m_path;
		m_query    = uri.m_query;
		m_fragment = uri.m_fragment;
	}
	return *this;
}

CURI& CURI::operator = (const std::string& uri)
{
	clear();
	parse(uri);
	return *this;
}

CURI& CURI::operator = (const char* uri)
{
	clear();
	parse(std::string(uri));
	return *this;
}

void CURI::swap(CURI& uri)
{
	std::swap(m_scheme,		uri.m_scheme);
	std::swap(m_userInfo,	uri.m_userInfo);
	std::swap(m_host,		uri.m_host);
	std::swap(m_port,		uri.m_port);
	std::swap(m_path,		uri.m_path);
	std::swap(m_query,		uri.m_query);
	std::swap(m_fragment,	uri.m_fragment);
}

void CURI::clear()
{
	m_scheme.clear();
	m_userInfo.clear();
	m_host.clear();
	m_port = 0;
	m_path.clear();
	m_query.clear();
	m_fragment.clear();
}

std::string CURI::toString() const
{
	std::string uri;
	if (isRelative())
	{
		encode(m_path, RESERVED_PATH, uri);
	}
	else
	{
		uri = m_scheme;
		uri += ':';
		std::string auth = getAuthority();
		if (!auth.empty() || m_scheme == "file")
		{
			uri.append("//");
			uri.append(auth);
		}
		if (!m_path.empty())
		{
			if (!auth.empty() && m_path[0] != '/')
				uri += '/';
			encode(m_path, RESERVED_PATH, uri);
		}
		else if (!m_query.empty() || !m_fragment.empty())
		{
			uri += '/';
		}
	}
	if (!m_query.empty())
	{
		uri += '?';
		uri.append(m_query);
	}
	if (!m_fragment.empty())
	{
		uri += '#';
		encode(m_fragment, RESERVED_FRAGMENT, uri);
	}
	return uri;
}

void CURI::setScheme(const std::string& scheme)
{
	m_scheme = scheme;
	toLowerInPlace(m_scheme);
	if (m_port == 0)
		m_port = getWellKnownPort();
}

const std::string& CURI::getScheme() const
{
	return m_scheme;
}

void CURI::setUserInfo(const std::string& userInfo)
{
	m_userInfo.clear();
	decode(userInfo, m_userInfo);
}

const std::string& CURI::getUserInfo() const
{
	return m_userInfo;
}

void CURI::setHost(const std::string& host)
{
	m_host = host;
}

const std::string& CURI::getHost() const
{
	return m_host;
}

void CURI::setPort(unsigned short port)
{
	m_port = port;
}

unsigned short CURI::getPort() const
{
	if (m_port == 0)
		return getWellKnownPort();
	else
		return m_port;
}

std::string CURI::getAuthority() const
{
	std::string auth;
	if (!m_userInfo.empty())
	{
		auth.append(m_userInfo);
		auth += '@';
	}
	if (m_host.find(':') != std::string::npos)
	{
		auth += '[';
		auth += m_host;
		auth += ']';
	}
	else auth.append(m_host);
	if (m_port && !isWellKnownPort())
	{
		auth += ':';
		CNumberFormatter::append(auth, m_port);
	}
	return auth;
}

void CURI::setAuthority(const std::string& authority)
{
	m_userInfo.clear();
	m_host.clear();
	m_port = 0;
	std::string::const_iterator beg = authority.begin();
	std::string::const_iterator end = authority.end();
	parseAuthority(beg, end);
}

void CURI::setPath(const std::string& path)
{
	m_path.clear();
	decode(path, m_path);
}

const std::string& CURI::getPath() const
{
	return m_path;
}

void CURI::setRawQuery(const std::string& query)
{
	m_query = query;
}

const std::string& CURI::getRawQuery() const
{
	return m_query;
}

void CURI::setQuery(const std::string& query)
{
	m_query.clear();
	encode(query, RESERVED_QUERY, m_query);
}

std::string CURI::getQuery() const
{
	std::string query;
	decode(m_query, query);
	return query;
}

void CURI::addQueryParameter(const std::string& param, const std::string& val)
{
	std::string reserved(RESERVED_QUERY);
	reserved += "=&";
	if (!m_query.empty()) m_query += '&';
	encode(param, reserved, m_query);
	m_query += '=';
	encode(val, reserved, m_query);
}

CURI::QueryParameters CURI::getQueryParameters() const
{
	QueryParameters result;
	std::string::const_iterator it(m_query.begin());
	std::string::const_iterator end(m_query.end());
	while (it != end)
	{
		std::string name;
		std::string value;
		while (it != end && *it != '=' && *it != '&')
		{
			if (*it == '+') 
				name += ' ';
			else
				name += *it;
			++it;
		}
		if (it != end && *it == '=')
		{
			++it;
			while (it != end && *it != '&')
			{
				if (*it == '+') 
					value += ' ';
				else
					value += *it;
				++it;
			}
		}
		std::string decodedName;
		std::string decodedValue;
		CURI::decode(name, decodedName);
		CURI::decode(value, decodedValue);
		result.push_back(std::make_pair(decodedName, decodedValue));
		if (it != end && *it == '&') ++it;	
	}
	return result;
}

void CURI::setQueryParameters(const QueryParameters& params)
{
	m_query.clear();
	for (QueryParameters::const_iterator it = params.begin(); it != params.end(); ++it)
	{
		addQueryParameter(it->first, it->second);
	}
}

void CURI::setFragment(const std::string& fragment)
{
	m_fragment.clear();
	decode(fragment, m_fragment);
}

void CURI::setPathEtc(const std::string& pathEtc)
{
	m_path.clear();
	m_query.clear();
	m_fragment.clear();
	std::string::const_iterator beg = pathEtc.begin();
	std::string::const_iterator end = pathEtc.end();
	parsePathEtc(beg, end);
}

std::string CURI::getPathEtc() const
{
	std::string pathEtc;
	encode(m_path, RESERVED_PATH, pathEtc);
	if (!m_query.empty())
	{
		pathEtc += '?';
		pathEtc += m_query;
	}
	if (!m_fragment.empty())
	{
		pathEtc += '#';
		encode(m_fragment, RESERVED_FRAGMENT, pathEtc);
	}
	return pathEtc;
}

std::string CURI::getPathAndQuery() const
{
	std::string pathAndQuery;
	encode(m_path, RESERVED_PATH, pathAndQuery);
	if (!m_query.empty())
	{
		pathAndQuery += '?';
		pathAndQuery += m_query;
	}
	return pathAndQuery;
}


void CURI::resolve(const std::string& relativeURI)
{
	CURI parsedURI(relativeURI);
	resolve(parsedURI);
}


void CURI::resolve(const CURI& relativeURI)
{
	if (!relativeURI.m_scheme.empty())
	{
		m_scheme   = relativeURI.m_scheme;
		m_userInfo = relativeURI.m_userInfo;
		m_host     = relativeURI.m_host;
		m_port     = relativeURI.m_port;
		m_path     = relativeURI.m_path;
		m_query    = relativeURI.m_query;
		removeDotSegments();
	}
	else
	{
		if (!relativeURI.m_host.empty())
		{
			m_userInfo = relativeURI.m_userInfo;
			m_host     = relativeURI.m_host;
			m_port     = relativeURI.m_port;
			m_path     = relativeURI.m_path;
			m_query    = relativeURI.m_query;
			removeDotSegments();
		}
		else
		{
			if (relativeURI.m_path.empty())
			{
				if (!relativeURI.m_query.empty())
					m_query = relativeURI.m_query;
			}
			else
			{
				if (relativeURI.m_path[0] == '/')
				{
					m_path = relativeURI.m_path;
					removeDotSegments();
				}
				else
				{
					mergePath(relativeURI.m_path);
				}
				m_query = relativeURI.m_query;
			}
		}
	}
	m_fragment = relativeURI.m_fragment;      
}

bool CURI::isRelative() const
{
	return m_scheme.empty();
}

bool CURI::empty() const
{
	return m_scheme.empty() && m_host.empty() && m_path.empty() && m_query.empty() && m_fragment.empty();
}

bool CURI::operator == (const CURI& uri) const
{
	return equals(uri);
}

bool CURI::operator == (const std::string& uri) const
{
	CURI parsedURI(uri);
	return equals(parsedURI);
}

bool CURI::operator != (const CURI& uri) const
{
	return !equals(uri);
}

bool CURI::operator != (const std::string& uri) const
{
	CURI parsedURI(uri);
	return !equals(parsedURI);
}

bool CURI::equals(const CURI& uri) const
{
	return m_scheme   == uri.m_scheme
		&& m_userInfo == uri.m_userInfo
		&& m_host     == uri.m_host
		&& getPort() == uri.getPort()
		&& m_path     == uri.m_path
		&& m_query    == uri.m_query
		&& m_fragment == uri.m_fragment;
}

void CURI::normalize()
{
	removeDotSegments(!isRelative());
}

void CURI::removeDotSegments(bool removeLeading)
{
	if (m_path.empty()) 
		return;

	bool leadingSlash  = *(m_path.begin()) == '/';
	bool trailingSlash = *(m_path.rbegin()) == '/';
	std::vector<std::string> segments;
	std::vector<std::string> normalizedSegments;
	getPathSegments(segments);
	for (std::vector<std::string>::const_iterator it = segments.begin(); it != segments.end(); ++it)
	{
		if (*it == "..")
		{
			if (!normalizedSegments.empty())
			{
				if (normalizedSegments.back() == "..")
					normalizedSegments.push_back(*it);
				else
					normalizedSegments.pop_back();
			}
			else if (!removeLeading)
			{
				normalizedSegments.push_back(*it);
			}
		}
		else if (*it != ".")
		{
			normalizedSegments.push_back(*it);
		}
	}
	buildPath(normalizedSegments, leadingSlash, trailingSlash);
}

void CURI::getPathSegments(std::vector<std::string>& segments)
{
	getPathSegments(m_path, segments);
}

void CURI::getPathSegments(const std::string& path, std::vector<std::string>& segments)
{
	std::string::const_iterator it  = path.begin();
	std::string::const_iterator end = path.end();
	std::string seg;
	while (it != end)
	{
		if (*it == '/')
		{
			if (!seg.empty())
			{
				segments.push_back(seg);
				seg.clear();
			}
		}
		else seg += *it;
		++it;
	}
	if (!seg.empty())
		segments.push_back(seg);
}

void CURI::encode(const std::string& str, const std::string& reserved, std::string& encodedStr)
{
	for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
	{
		char c = *it;
		if ((c >= 'a' && c <= 'z') || 
			(c >= 'A' && c <= 'Z') || 
			(c >= '0' && c <= '9') ||
			c == '-' || c == '_' || 
			c == '.' || c == '~')
		{
			encodedStr += c;
		}
		else if (c <= 0x20 || c >= 0x7F || ILLEGAL.find(c) != std::string::npos || reserved.find(c) != std::string::npos)
		{
			encodedStr += '%';
			encodedStr += CNumberFormatter::formatHex((unsigned) (unsigned char) c, 2);
		}
		else encodedStr += c;
	}
}

void CURI::decode(const std::string& str, std::string& decodedStr, bool plusAsSpace)
{
	bool inQuery = false;
	std::string::const_iterator it  = str.begin();
	std::string::const_iterator end = str.end();
	while (it != end)
	{
		char c = *it++;
		if (c == '?') inQuery = true;
		// spaces may be encoded as plus signs in the query
		if (inQuery && plusAsSpace && c == '+') c = ' ';
		else if (c == '%')
		{
			if (it == end) throw SyntaxException("URI encoding: no hex digit following percent sign", str);
			char hi = *it++;
			if (it == end) throw SyntaxException("URI encoding: two hex digits must follow percent sign", str);
			char lo = *it++;
			if (hi >= '0' && hi <= '9')
				c = hi - '0';
			else if (hi >= 'A' && hi <= 'F')
				c = hi - 'A' + 10;
			else if (hi >= 'a' && hi <= 'f')
				c = hi - 'a' + 10;
			else throw SyntaxException("URI encoding: not a hex digit");
			c *= 16;
			if (lo >= '0' && lo <= '9')
				c += lo - '0';
			else if (lo >= 'A' && lo <= 'F')
				c += lo - 'A' + 10;
			else if (lo >= 'a' && lo <= 'f')
				c += lo - 'a' + 10;
			else throw SyntaxException("URI encoding: not a hex digit");
		}
		decodedStr += c;
	}
}

bool CURI::isWellKnownPort() const
{
	return m_port == getWellKnownPort();
}

unsigned short CURI::getWellKnownPort() const
{
	if (m_scheme == "ftp")
		return 21;
	else if (m_scheme == "ssh")
		return 22;
	else if (m_scheme == "telnet")
		return 23;
	else if (m_scheme == "http")
		return 80;
	else if (m_scheme == "nntp")
		return 119;
	else if (m_scheme == "ldap")
		return 389;
	else if (m_scheme == "https")
		return 443;
	else if (m_scheme == "rtsp")
		return 554;
	else if (m_scheme == "sip")
		return 5060;
	else if (m_scheme == "sips")
		return 5061;
	else if (m_scheme == "xmpp")
		return 5222;
	else
		return 0;
}

void CURI::parse(const std::string& uri)
{
	std::string::const_iterator it  = uri.begin();
	std::string::const_iterator end = uri.end();
	if (it == end) return;
	if (*it != '/' && *it != '.' && *it != '?' && *it != '#')
	{
		std::string scheme;
		while (it != end && *it != ':' && *it != '?' && *it != '#' && *it != '/') scheme += *it++;
		if (it != end && *it == ':')
		{
			++it;
			if (it == end) throw SyntaxException("URI scheme must be followed by authority or path", uri);
			setScheme(scheme);
			if (*it == '/')
			{
				++it;
				if (it != end && *it == '/')
				{
					++it;
					parseAuthority(it, end);
				}
				else --it;
			}
			parsePathEtc(it, end);
		}
		else 
		{
			it = uri.begin();
			parsePathEtc(it, end);
		}
	}
	else parsePathEtc(it, end);
}

void CURI::parseAuthority(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	std::string userInfo;
	std::string part;
	while (it != end && *it != '/' && *it != '?' && *it != '#')
	{
		if (*it == '@')
		{
			userInfo = part;
			part.clear();
		}
		else part += *it;
		++it;
	}
	std::string::const_iterator pbeg = part.begin();
	std::string::const_iterator pend = part.end();
	parseHostAndPort(pbeg, pend);
	m_userInfo = userInfo;
}

void CURI::parseHostAndPort(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	if (it == end) return;
	std::string host;
	if (*it == '[')
	{
		// IPv6 address
		++it;
		while (it != end && *it != ']') host += *it++;
		if (it == end) throw SyntaxException("unterminated IPv6 address");
		++it;
	}
	else
	{
		while (it != end && *it != ':') host += *it++;
	}
	if (it != end && *it == ':')
	{
		++it;
		std::string port;
		while (it != end) port += *it++;
		if (!port.empty())
		{
			int nport = 0;
			if (CNumberParser::tryParse(port, nport) && nport > 0 && nport < 65536)
				m_port = (unsigned short) nport;
			else
				throw SyntaxException("bad or invalid port number", port);
		}
		else m_port = getWellKnownPort();
	}
	else m_port = getWellKnownPort();
	m_host = host;
	toLowerInPlace(m_host);
}

void CURI::parsePath(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	std::string path;
	while (it != end && *it != '?' && *it != '#') path += *it++;
	decode(path, m_path);
}

void CURI::parsePathEtc(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	if (it == end) return;
	if (*it != '?' && *it != '#')
		parsePath(it, end);
	if (it != end && *it == '?')
	{
		++it;
		parseQuery(it, end);
	}
	if (it != end && *it == '#')
	{
		++it;
		parseFragment(it, end);
	}	
}

void CURI::parseQuery(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	m_query.clear();
	while (it != end && *it != '#') m_query += *it++;
}

void CURI::parseFragment(std::string::const_iterator& it, const std::string::const_iterator& end)
{
	std::string fragment;
	while (it != end) fragment += *it++;
	decode(fragment, m_fragment);
}

void CURI::mergePath(const std::string& path)
{
	std::vector<std::string> segments;
	std::vector<std::string> normalizedSegments;
	bool addLeadingSlash = false;
	if (!m_path.empty())
	{
		getPathSegments(segments);
		bool endsWithSlash = *(m_path.rbegin()) == '/';
		if (!endsWithSlash && !segments.empty())
			segments.pop_back();
		addLeadingSlash = m_path[0] == '/';
	}
	getPathSegments(path, segments);
	addLeadingSlash = addLeadingSlash || (!path.empty() && path[0] == '/');
	bool hasTrailingSlash = (!path.empty() && *(path.rbegin()) == '/');
	bool addTrailingSlash = false;
	for (std::vector<std::string>::const_iterator it = segments.begin(); it != segments.end(); ++it)
	{
		if (*it == "..")
		{
			addTrailingSlash = true;
			if (!normalizedSegments.empty())
				normalizedSegments.pop_back();
		}
		else if (*it != ".")
		{
			addTrailingSlash = false;
			normalizedSegments.push_back(*it);
		}
		else addTrailingSlash = true;
	}
	buildPath(normalizedSegments, addLeadingSlash, hasTrailingSlash || addTrailingSlash);
}

void CURI::buildPath(const std::vector<std::string>& segments, bool leadingSlash, bool trailingSlash)
{
	m_path.clear();
	bool first = true;
	for (std::vector<std::string>::const_iterator it = segments.begin(); it != segments.end(); ++it)
	{
		if (first)
		{
			first = false;
			if (leadingSlash)
				m_path += '/';
			else if (m_scheme.empty() && (*it).find(':') != std::string::npos)
				m_path.append("./");
		}
		else m_path += '/';
		m_path.append(*it);
	}
	if (trailingSlash) 
		m_path += '/';
}

NET_NAMESPACE_END
